package bz.yfw.example.s3blazeds.part1.behavior
{
	import bz.yfw.example.s3blazeds.part1.helper.TopHelper;
	import bz.yfw.example.s3blazeds.part1.service.PingService;
	import bz.yfw.example.s3blazeds.part1.service.SampleModelService;
	
	import com.google.appengine.api.datastore.Key;
	
	import flash.utils.getTimer;
	
	import org.seasar.akabana.yui.framework.ns.handler;
	import org.seasar.akabana.yui.service.ds.RemotingService;
	import org.seasar.akabana.yui.service.event.FaultStatus;
	import org.seasar.akabana.yui.service.ns.rpc_fault;
	import org.seasar.akabana.yui.service.ns.rpc_result;
	
	import slim3.model.SampleModel;
	import slim3.model.SampleModelCreator;

	public class TopSendBehavior
	{
		public var helper:TopHelper;
		public var pingService:PingService;
		public var sampleModelService:SampleModelService;
		private var startTime:uint = 0;
		
		handler function btnSend_click():void {
			var selected:String = helper.selectedRadioValue;
			startTime = getTimer();
			switch (selected) {
				case "ping":
					pingService.ping(helper.inputText).setResponder(this);
					break;
				case "get":
					sampleModelService.get(SampleModelCreator.getKey()).setResponder(this);
					break;
				case "put":
					sampleModelService.put(
						SampleModelCreator.getModel(helper.inputText)).setResponder(this);
					break;
			}
			helper.connect();
		}
		
		rpc_result function pingService_ping(result:String):void {
			doResult("通信に成功しました " + getTime(), result);
		}
		
		rpc_fault function pingService_ping(fault:FaultStatus):void {
			doFault(fault);
		}
		
		rpc_result function sampleModelService_get(result:SampleModel):void {
			doResult("取得に成功しました" + getTime(), result.key + result.text);
		}
		
		rpc_fault function sampleModelService_get(fault:FaultStatus):void {
			doFault(fault);
		}
		
		rpc_result function sampleModelService_put(result:Key):void {
			doResult("登録完了しました" + getTime(),result.toString());
		}
		
		rpc_fault function sampleModelService_put(fault:FaultStatus):void {
			doFault(fault);
		}
		
		private function doResult(message:String, result:String):void {
			helper.result = result;
			helper.exitSend(message);
		}
		
		private function doFault(fault:FaultStatus):void {
			helper.result = 
				fault.code + fault.details + fault.description;
			helper.exitSend("サーバーエラー発生" + getTime());
		}
		
		private function getTime():String {
			var time:uint = getTimer() - startTime;
			var second:uint = time / 1000;
			var m:uint = time % 1000;
			return " " + second + "秒" + m + "ms";
		}
	}
}